package satellite

import (
	"errors"
)

var (
	EmptyConnError = errors.New("conn is empty")
)

// 实现allow多个链接
type AllowMulti struct {
	allowConn []Conn
}

func NewAllowMulti(transports TransportTypeSlice) *AllowMulti {
	a := &AllowMulti{
		allowConn: make([]Conn, len(transports)),
	}
	return a
}

func (a *AllowMulti) Connect(transportIndex int, conn Conn) {
	old := a.allowConn[transportIndex]
	if old != nil {
		_ = old.Close()
	}
	a.allowConn[transportIndex] = conn
}

func (a *AllowMulti) SelectConn(transportIndex int) (Conn, error) {
	//fmt.Println(c.allowConn, protocolType)
	var conn Conn
	if transportIndex >= 0 {
		conn = a.allowConn[transportIndex]
	}
	if conn == nil || !conn.Connected() {
		for k, _ := range a.allowConn {
			if a.allowConn[k] != nil {
				conn = a.allowConn[k]
				break
			}
			// 客户端根据网络情况决定
			// 安全性链接走nebula协议实现单链接
			//c.OnProtocol(protocolTmp, protocolType)
		}
	}
	if conn == nil || !conn.Connected() {
		a.allowConn[transportIndex] = nil
		return nil, EmptyConnError
	}
	return conn, nil
}

func (a *AllowMulti) OnClose(transportIndex int) int {
	if old := a.allowConn[transportIndex]; old != nil {
		a.allowConn[transportIndex] = nil
	}
	index := -1
	for k, _ := range a.allowConn {
		if a.allowConn[k] != nil {
			index = k
			break
		}
	}
	return index
}

func (a *AllowMulti) Close() {
	for k, _ := range a.allowConn {
		if a.allowConn[k] != nil {
			_ = a.allowConn[k].Close()
		}
	}
}
